import Taro, { Component } from '@tarojs/taro'
import {View, ScrollView, Text, Image} from '@tarojs/components'
import { connect } from '@tarojs/redux'
import {AtActionSheet, AtActionSheetItem, AtButton, AtSearchBar} from 'taro-ui'
import { asyncLoadDaily, setKeyword, reSetList } from '../../actions/daily'
import './index.styl'
import { ListGoodItem } from "../../components/listGoodItem/index"

import withShare from '../../components/withShare'
import Poster from '../../components/poster/poster/poster'
import Poster2 from '../../components/poster/poster/posterfull'
import defaultShareImg from '../../assets/images/share.jpg';
import shareCodeImg from '../../assets/images/code.jpeg';
import cartImg from '../../assets/images/tabbar/tab-cart.png'
import shareCardBg from '../../assets/images/sharecardbg.png'
import locationImg from '../../assets/images/pin.png'
import shopImg from '../../assets/images/shop.png'
import discountIcon from '../../assets/images/discount.png'

// import pinImg from '../../assets/images/pin.png'
import {GoodItem} from "../index";

/**
 * TODO 1. 加上底部加载更多的提示
 */
@withShare({})
@connect(({ daily, cart, shop, user }) => ({
  daily, cart, shop, user
}), (dispatch) => ({
  // 加载每日鲜果
  onAsyncDaily () {
    dispatch(asyncLoadDaily())
  },
  // 设置关键词
  onSetKeyword (word) {
    dispatch(setKeyword(word))
  },
  // 搜索前准备
  onStartSearch () {
    dispatch(reSetList())
  }
}))
class Daily extends Component {
  constructor () {
    super(...arguments)
    this.state = {
      posterConfig : {
        width: 1000,
        height: 800,
        backgroundColor: '#fff',
        debug: false,
        images: [
          {
            url: defaultShareImg,
            width: 800,
            height: 800,
            y: 0,
            x: 100,
          }
        ]
      },
      posterConfig2: {
        width: 750,
        height: 1334,
        backgroundColor: '#fff',
        debug: false,
        texts: [
          // 名称
          {
            x: 750 / 2,
            y: 750 * 1.1,
            text: `社区生活家`,
            fontSize: Math.floor(750 * 0.06),
            color: '#555',
            opacity: 1,
            zIndex: 9,
            textAlign: 'center',
            width: 650
          },
          // 价格
          {
            x: 750 / 2,
            y: 750 * 1.17,
            text: `新鲜低价`,
            fontSize:  Math.floor(750 * 0.05),
            color: '#FD7474',
            opacity: 1,
            zIndex: 9,
            textAlign: 'center',
            width: 650
          },
          // 描述
          {
            x: 750 / 2,
            y: 750 * 1.24 -20,
            text: `长按识别小程序二维码`,
            fontSize: Math.floor(750 * 0.04),
            color: '#B2B2B2',
            opacity: 1,
            zIndex: 9,
            textAlign: 'center',
            width: 650
          },
        ],
        images: [
          {
            url:  defaultShareImg,
            width: 750,
            height: 750,
            y: 0,
            x: 0,
          },
          {
            url: shareCodeImg,
            width: 750 * .4,
            height: 750 * .4,
            y: 750 * 1.3,
            x: Math.floor(750 * .3),
          }
        ]
      },
      shareActionSheetOpen: false, // 打开分享弹窗
      shareImg: defaultShareImg,
      posterImg: '',
      shareitem: {}
    }
  }

  config = {
    navigationBarTitleText: '每日鲜果',
    onReachBottomDistance: 300,
    usingComponents: {
      'poster': '../../components/poster/poster/index',
    }
  }

  // 设置分享标题
  $setShareTitle = () => {
    const {  name, spec_name } = this.state.shareitem
    return spec_name ? `${name}` : `${name}`
  }

  // 设置分享图
  $setShareImageUrl = () => {
    const {  shareImg } = this.state
    return shareImg
  }

  // 设置搜索关键词
  onSearchValueChange (value) {
    this.props.onSetKeyword(value)
  }

  // 点击搜索
  onSearchActionClick () {
    this.props.onStartSearch()
    this.props.onAsyncDaily() // 加载每日鲜果
  }

  // 下拉刷新
  onPullDownRefresh () {
    Taro.stopPullDownRefresh()
    this.props.onSetKeyword('')
    this.props.onStartSearch() // 重置
    this.props.onAsyncDaily() // 加载每日鲜果
  }

  // 页面到达底部
  onReachBottom () {
    console.log('onReachBottom')
    const {nomore} = this.props.daily
    if (nomore) return
    this.props.onAsyncDaily() // 加载每日鲜果
  }

  // 点击封面
  onThumbClick (shareitem, e) {
    console.log("点击封面")
    console.log(e)
    console.log(this)
    e.preventDefault()
    e.stopPropagation()
    const  {thumb, price, weight, spec_name, goodId } = shareitem
    console.log(goodId)
    console.log(shareitem)
    this.setState({
      shareitem,
      posterConfig: {
        width: 1000,
        height: 800,
        backgroundColor: '#fff',
        debug: false,
        blocks: [
          {
            x: 0,
            y: 600,
            width: 1000, // 如果内部有文字，由文字宽度和内边距决定
            height: 200,
            paddingLeft: 0,
            paddingRight: 0,
            borderWidth: 0,
            backgroundColor: '#FFC93E',
            borderRadius: 40,
            zIndex: 1,
          },
          {
            x: 0,
            y: 760,
            width: 40,
            height: 40,
            paddingLeft: 0,
            paddingRight: 0,
            borderWidth: 0,
            backgroundColor: '#FFC93E',
            borderRadius: 0
          },
          {
            x: 960,
            y: 760,
            width: 40,
            height: 40,
            paddingLeft: 0,
            paddingRight: 0,
            borderWidth: 0,
            backgroundColor: '#FFC93E',
            borderRadius: 0
          }
        ],
        texts: [
          {
            x: 50,
            y: 660,
            text: [
              {
                text: `¥ ${parseFloat(price / 100).toFixed(2)}`,
                fontSize: 80,
                color: 'white',
                opacity: 1,
                marginLeft: 0,
                marginRight: 40,
                lineHeight: 140,
                lineNum: 1,
              },
              // {
              //   text: `原价¥ ${parseFloat(origin_price / 100).toFixed(2)}`,
              //   fontSize: 50,
              //   color: 'white',
              //   opacity: 1,
              //   marginLeft: 10,
              //   textDecoration: 'line-through',
              // },
            ],
            zIndex: 9,
            baseLine: 'middle',
          },
          {
            x: 50,
            y: 740,
            text: `${weight}g/${spec_name}`,
            fontSize: 50,
            color: 'white',
            opacity: 1,
            baseLine: 'middle',
            zIndex: 9,
          },
        ],
        images: [
          {
            url: thumb || defaultShareImg,
            width: 800,
            height: 800,
            y: 0,
            x: 100,
          },
          {// 满减图标
            url: discountIcon,
            width: 160,
            height: 120,
            y: 20,
            x:20,
            zIndex: 9,
          }
        ]
      }
    })
    setTimeout(() => {
      Poster.create(true)    // 入参：true为抹掉重新生成
    }, 200)
    Taro.showLoading({})

  }

  onPosterSuccess (preview, e) {
    const { detail } = e;
    Taro.hideLoading()
    // 预览
    if (preview === 'poster') {
      console.log('生成海报成功')
      this.setState({
        posterImg: detail,
        shareActionSheetOpen: false
      })
      Taro.previewImage({
        current: detail,
        urls: [detail]
      })
    }
    // 分享
    if (preview === 'share') {
      console.log('生成分享图成功666')
      console.log(this)
      this.setState({
        shareImg: detail,
        shareActionSheetOpen: true
      })
    }
  }

  onPosterFail () {
    console.log('失败')
    Taro.hideLoading()
  }

  handleActionSheetOpen () {
    this.setState({
      shareActionSheetOpen: true
    })
  }

  // 分享actionsheet 关闭
  handleActionSheetClose () {
    this.setState({
      shareActionSheetOpen: false
    })
  }

  // 分享actionsheet 取消
  handleActionSheetCancel () {
    this.setState({
      shareActionSheetOpen: false,
      shareImg: defaultShareImg
    })
  }

  // 分享actionsheet 点击
  handleActionSheetClick (type) {
    this.setState({
      shareActionSheetOpen: false
    })
    if (type === 'poster') {
      console.log(this.state.shareitem)

      const { name, spec_name, thumb, price, weight, tags, shopAdd} = this.state.shareitem
      console.log(this.state.shareitem)
      const {avatar, nickname} = this.props.user
      console.log( this.props.daily.list)
      Taro.getSystemInfo({}).then(({screenWidth, screenHeight, pixelRatio}) => {
        console.log(screenWidth, screenHeight, pixelRatio)
        const width = screenWidth * pixelRatio
        const height = Math.max(screenHeight * pixelRatio, Math.floor(width * 2.1))
        const codeWidth = Math.floor(width * .4)
        const topheight = 150
        const infoblockH = width * 0.6 + 390 + topheight
        const textxLeft = 40
        let tags_width = 0
        this.setState({
          posterConfig2: {
            width,
            height:height - 50,
            y: topheight,
            backgroundColor: '#000',
            debug: false,
            blocks: [{
              // 商品规格
              x: width - 230,
              y: width * 0.6 + 210 + topheight,
              width: 210,
              height: Math.floor(width * 0.04) * 1.5,
              text: {
                text: `${weight}g/${spec_name}`,
                fontSize: Math.floor(width * 0.04),
                lineHeight: Math.floor(width * 0.04) * 1.5,
                color: '#0f59a4',
                opacity: 1,
                zIndex: 9,
                textAlign: 'right',
              }
            },
              // tags
              ...tags.map((tag, index) => {
                const  fontSize = Math.floor(width * 0.03)
                const tag_width = fontSize * tag.name.length * 1.1 + 40
                const tag_height = fontSize * 1.5
                tags_width = tags_width + tag_width + 30
                return {
                  x: tags_width - tag_width,
                  y: width * 0.6 + 260 + topheight,
                  width: tag_width,
                  height: tag_height,
                  backgroundColor: 'transparent',
                  borderRadius: 10,
                  borderWidth:2,
                  borderStyle:'solid',
                  borderColor:'#FFD701',
                  zIndex: 9,
                  text: {
                    text: `${tag.name}`,
                    fontSize: fontSize,
                    lineHeight: fontSize * 1.5,
                    color: '#333',
                    opacity: 1,
                    textAlign: 'center',
                    baseLine: 'middle'
                  }
                }
              }),
              // 分界线
              {
                  width: width * 0.92,
                  height: 1,
                  x: width * 0.05,
                  y: width * 0.6 + 320 + topheight,
                  backgroundColor: '#C7C7C7',
                  opacity: 1,
                  zIndex: 9,
              },
            ],
            texts: [
              {
                // 微信昵称
                x: 130,
                y: 70 + topheight,
                text: nickname,
                fontSize: Math.floor(width * 0.05),
                lineHeight: 80,
                baseLine: 'middle',
                color: '#555',
                opacity: 1,
                zIndex: 9,
                textAlign: 'left',
                width: width - 160
              },
              // 商品名称
              {
                x: textxLeft,
                y: width * 0.6 + 230 + topheight,
                text: `${name}`,
                fontSize: Math.floor(width * 0.05),
                color: '#555',
                opacity: 1,
                zIndex: 9,
                textAlign: 'left',
                width: width - 260
              },
              //价格
                {
                    x: textxLeft,
                    y: width * 0.6 + 360 + topheight,
                    baseLine: 'middle',
                    textAlign: 'left',
                    opacity: 1,
                    zIndex: 9,
                    text: [
                        {
                            text: `¥ ${parseFloat(price / 100).toFixed(2)}`,
                            fontSize: Math.floor(width * 0.06),
                            color: '#ec1731',
                            marginLeft: 0,
                        }
                       
                    ]
                },
              // 描述
              {
                x: width / 2,
                y: width * 2 + topheight,
                text: `长按识别小程序二维码`,
                fontSize: Math.floor(width * 0.04),
                color: '#B2B2B2',
                opacity: 1,
                zIndex: 9,
                textAlign: 'center',
                width: width - 100
              },
              // 店铺名称
              {
                x: 50 +Math.floor(width * 0.2),
                y: width * 1.29 + topheight,
                text: `${shopAdd.name}`,
                fontSize: Math.floor(width * 0.04),
                color: '#515151',
                opacity: 1,
                zIndex: 9,
                textAlign: 'left',
                baseLine: 'bottom',
                width: width - 80 - Math.floor(width * 0.05)
              },
              // 店铺地址
              {
                x: 50 + Math.floor(width * 0.06),
                y: width * 1.39 + topheight,
                lineHeight: Math.floor(width * 0.04)+10,
                text: `${shopAdd.address}`,
                fontSize: Math.floor(width * 0.04),
                height:Math.floor(width * 0.04),
                color: '#515151',
                opacity: 1,
                zIndex: 9,
                textAlign: 'left',
                baseLine: 'bottom',
                width: width - 80 - Math.floor(width * 0.05)
              },
            ],
            images: [
              { // 背景图片
                url: shareCardBg,
                width: width,
                height: height - 50,
                position: 'absolute',
                y: topheight,
                x: 0,
                zIndex: 0,

              },
              { // 商品大图
                  url: thumb || defaultShareImg,
                  width: width * 0.8,
                  height: width * 0.6 ,
                  y: 150 + topheight,
                  x: width * 0.1,
              },
              { // 用户头像
                url: avatar ,
                width: 80,
                height: 80,
                y: 30 + topheight,
                x: textxLeft,
                borderRadius: 80,
                // borderWidth: 1
              },
              { // shop图标
                url: shopImg,
                width: Math.floor(width * 0.05),
                height: Math.floor(width * 0.05),
                y: width * 1.24 + topheight,
                x: textxLeft
              },
              { // 位置 图标
                  url: locationImg,
                  width: Math.floor(width * 0.05),
                  height: Math.floor(width * 0.05),
                  y: width * 1.34 + topheight,
                  x: textxLeft
              },
              { // 拼图标
                url: discountIcon,
                width: Math.floor(width * 0.2),
                height: Math.floor(width * 0.08),
                y: infoblockH,
                x: textxLeft
            },
              { // 二维码图
                url: shareCodeImg,
                width: codeWidth,
                height: codeWidth,
                y: width * 1.5 + topheight,
                x: Math.floor(width * .3),
              }
            ]
          }
        })
        setTimeout(() => {
          Poster2.create(true)    // 入参：true为抹掉重新生成
        }, 200)
      })
    }
  }


  // 去购物车
  toCart () {
    Taro.switchTab({
      url: '/pages/cart/index'
    })
  }
  componentWillReceiveProps (nextProps) {
    console.log(this.props, nextProps)
  }
  componentDidMount () {
    this.props.onSetKeyword('')
    this.props.onStartSearch() // 重置
    this.props.onAsyncDaily() // 加载每日鲜果
  }
  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  render () {
    const {list, search} = this.props.daily
    const {cart_num} = this.props.cart
    const { num, posterConfig, posterConfig2, shareActionSheetOpen } = this.state

    const renderDailyList = list.map((item, index) => {
      return (
        <ListGoodItem
          key={index}
          goodId={item.id}
          tags={item.tags}
          thumb={item.thumb}
          name={item.name}
          sales={item.sales}
          star={item.point}
          offer={item.offer}
          price={item.sale_price}
          sale_price={item.sale_price}
          origin_price={item.origin_price}
          spec_name={item.spec.name}
          weight={item.weight}
          original_price={item.original_price}
          shopAdd={item.shop}
          onThumbClick={this.onThumbClick.bind(this)}
        />
      )
    })

    return (
      <View className='daily'>
        <AtSearchBar
          fixed
          value={search}
          onChange={this.onSearchValueChange.bind(this)}
          onActionClick={this.onSearchActionClick.bind(this)}
        />
        <View className='discount'>满36减6 满54减9 </View>
        <ScrollView
          className='daily-list'
          enableBackToTop
          scrollY
          scrollWithAnimation
          scrollTop='0'
        >
          {renderDailyList}
        </ScrollView>

        {/*海报生成器*/}
        <poster
          id='poster'
          config={posterConfig}
          onSuccess={this.onPosterSuccess.bind(this, 'share')}
          onFail={this.onPosterFail.bind(this)}
        />

        {/*全屏海报生成器*/}
        <poster
          id='poster2'
          config={posterConfig2}
          onSuccess={this.onPosterSuccess.bind(this, 'poster')}
          onFail={this.onPosterFail.bind(this)}
        />

        {/*actionsheet*/}
        <AtActionSheet
          isOpened={shareActionSheetOpen}
          cancelText='取消'
          onCancel={this.handleActionSheetCancel.bind(this)}
          onClose={this.handleActionSheetClose.bind(this)}
        >
          <AtActionSheetItem onClick={this.handleActionSheetClick.bind(this, 'share')}>
            <AtButton openType='share' className='share-action-btn'>
              <Text className='text'>分享</Text>
            </AtButton>
          </AtActionSheetItem>
          <AtActionSheetItem onClick={this.handleActionSheetClick.bind(this, 'poster')}>
            <AtButton className='share-action-btn'>
              <Text className='text'>生成卡片保存分享</Text>
            </AtButton>
          </AtActionSheetItem>
        </AtActionSheet>

        {/*购物车图标*/}
        <View className='list-cart' onClick={this.toCart.bind(this)}>
          <Image src={cartImg} className='list-cart-img' />
          { cart_num > 0 && <View className='list-cart-badge'>{cart_num > 99 ? '99' : cart_num}</View> }
        </View>

      </View>
    )
  }
}

export default Daily
